import style from '../css/Login.module.scss'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, Flex, message } from 'antd';
import { useContext, useEffect, useState } from 'react';
import { capthcha, login } from '../utils/request';
import { useNavigate } from 'react-router';
import { context } from '../components/AppProvider';

const Ipt: React.FC = () => {
    const {resetMenus} = useContext(context)
    const [form] = Form.useForm();
    const navigate = useNavigate()
    const [vercode,setVercode]=useState<any>({
        text:'',
        data:'',
    }) 
    // 获取图形验证码
    const getCaptcha = () =>{
        capthcha().then(res=>{
            setVercode(res.data)
            console.log(res.data.text)
        }).catch(err=>{
            console.log(err)
        })
        form.resetFields(['vercode'])
    }
    useEffect(()=>{
        getCaptcha()
    },[])
    // 登录
    const [messageApi, contextHolder] = message.useMessage();
    const loginBTN=()=>{
        form.validateFields().then(values => {
            console.log('Validated values: ', values);
            messageApi.open({
                    type: 'loading',
                    content: '登录中..',
                    duration: 2,
                }).then(() => {
                    login(
                        values
                    ).then((res) =>{
                        console.log(res,1111)
                        if(res.data.token){
                            localStorage.setItem('token',res.data.token)
                            message.success('登录成功', 2.5)
                            resetMenus('admin')
                            navigate('/index/indexcontent')
                        }
                    }).catch(err=>{
                        console.log(err ,3333333)
                        message.error('账号或密码错误，请重新输入')
                        form.resetFields()
                        getCaptcha()
                    })
                    
                })
            
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    }

    return (
        <Form
            name="login"
            initialValues={{ remember: true }}
            style={{ maxWidth: 300 }}
            form={form}
        >
            <Form.Item
                name="username"
                rules={[{ required: true, message: '用户名不能为空!' }]}
            >
                <Input prefix={<UserOutlined />} placeholder="请输入用户名 (admin)" className={style.user} />
            </Form.Item>
            <Form.Item
                name="password"
                rules={[
                    { required: true, message: '密码不能为空!' },
                ]}
            >
                <Input.Password prefix={<LockOutlined />} type="password" placeholder="请输入密码 (123)" className={style.user} />
            </Form.Item>
            {/* <Form.Item className={style.lastItem}> */}
                <Flex justify="space-between" align="center">
                    <Form.Item
                        name="vercode"
                        rules={[
                            { required: true, message: '验证码不能为空!' },
                            {
                                validator: (_, value) => {
                                    if(value!=undefined){
                                        if (value.toLowerCase()!=vercode.text.toLowerCase()) {
                                            return Promise.reject(new Error('验证码错误!'));
                                        }else{
                                            return Promise.resolve();
                                        }
                                    }else{
                                        return Promise.resolve();
                                    }
                                    
                                }
                            }
                        ]}
                    >
                        <Input placeholder="请输入验证码" className={style.Code} />
                    </Form.Item>
                    <div className={style.verCode} onClick={()=>getCaptcha()} dangerouslySetInnerHTML={{__html:vercode.data}}>
                    </div>
                </Flex>
            {/* </Form.Item> */}
            <Form.Item>
                <Flex justify="space-between" align="center">
                    <Form.Item name="remember" valuePropName="checked" noStyle>
                        <Checkbox>记住密码</Checkbox>
                    </Form.Item>
                    <a href="">忘记密码？</a>
                </Flex>
            </Form.Item>
            {contextHolder}
            <Form.Item>
                <Button block type="primary" onClick={()=>loginBTN()} htmlType="submit" className={style.login_btn}>
                    登录
                </Button>
                {/* or <a href="">Register now!</a> */}
            </Form.Item>
        </Form>
    );
};
function Login() {
    return (
        <>
            <div className={style.bg}>
                <div className={style.login_dialogue}>
                    <div className={style.left_bg}>
                        <img className={style.poster} src="src/assets/loginbg.png" alt="" />
                    </div>
                    <div className={style.right_bg}>
                        <p className={style.system_name}>门诊挂号管理系统</p>
                        <p className={style.system_desc}>数字引领医疗信息时代</p>
                        <div className={style.loging_ipt}>
                            <Ipt></Ipt>
                        </div>
                    </div>
                </div>
                <div className={style.login_info}>Copyright © StarYun. All Rights Reserved </div>
            </div>
        </>
    );
}

export default Login;